import React from 'react';
import { connect } from 'dva';
import { Link, browserHistory } from 'dva/router';
import { Table, Row, Col, Form, Input, Radio, Button, Popconfirm, DatePicker } from 'antd';
const { RangePicker } = DatePicker;
const R = require('ramda');
import BizParams from '../../../components/commons/BizParams'
import OrderDeclareDetail from '../../../components/order/components/OrderDeclareDetail';
import RightBox from '../../../components/commons/RightBox';
import RightConstants from '../../../utils/RightConstants';
import Clearance from '../../../components/order/components/Clearance'
import Constants from '../../../utils/Constants';
import { download } from '../../../utils/commons'

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
export default connect(({ declareApproval, declaration, customs }) => ({ declareApproval, declaration, customs }))(
    Form.create()(class DeclareApproval extends React.Component {
        constructor(props) {
            super(props);
        }

        componentDidMount() {
            this.props.dispatch({ type: 'declareApproval/queryOrderManageList', payload: {} });//查询订单列表
        }

        collectSearchCondition = () => {
            let conditions = this.props.form.getFieldsValue();
            conditions.submitBegin = conditions.submitTime ? conditions.submitTime[0].format(Constants.DATEFORMAT) : undefined,
            conditions.submitEnd = conditions.submitTime ? conditions.submitTime[1].format(Constants.DATEFORMAT) : undefined,
            conditions.submitTime = undefined;
            conditions.page = this.props.declareApproval.page;
            return conditions;
        }

        onView = (record) => {
            this.handleOpenOrderDetail(record, true, true, true, true, {}, "1");
        }

        onCreateImportCD = (record) => {
            this.handleOpenOrderDetail(record, false, true, true, true, this.collectSearchCondition(), "5");
        }

        onGenerateImportCD = (record) => {
            this.handleOpenOrderDetail(record, false, true, true, true, this.collectSearchCondition(), "5");
        }

        onEditCost = (record) => {
            this.handleOpenOrderDetail(record, true, false, true, true, this.collectSearchCondition(), "6");
        }

        onEditClearance = (record) => {
            this.handleOpenOrderDetail(record, true, true, false, true, this.collectSearchCondition(), "7");
        }

        onReDownload = (record) => {
            let url = apiPath.imagent + "/api/order/" + record.id + "/generateDeclareInfo";
            download(url, { status: record.status });
        }

        onManageAttachment = (record) => {
            this.handleOpenOrderDetail(record, true, true, true, false, this.collectSearchCondition(), "4");
        }

        handleOpenOrderDetail = (record, importCDDisabled, costDisabled, clearanceDisabled, attachmentDisabled, searchConditions, tabActiveKey) => {
            this.props.dispatch({ type: 'declareApproval/getOrderById', payload: { id: record.id } });//获取订单详情
            this.props.dispatch({ type: 'declareApproval/queryLinkmanList', payload: { cstId: record.cstId } });//查询联系人列表
            this.props.dispatch({ type: 'customs/getListForPage', payload: { page: Constants.DEFAULT_PAGE } }); //查询海关信息
            this.props.dispatch({ type: 'orderCost/queryOrderCost', payload: { orderId: record.id, status: "1" } });//查询费用列表
            this.props.dispatch({ type: 'declareApproval/queryTgManagers' });//查询通关专员
            this.refs.orderDeclareDetail.handleOpen(importCDDisabled, costDisabled, clearanceDisabled, attachmentDisabled, searchConditions, tabActiveKey);
        }

        handleSearch = (flag) => {
            let values = this.props.form.getFieldsValue();
            let newPage = this.props.declareApproval.page;
            if (flag) newPage.page = 1;
            this.props.dispatch({
                type: 'declareApproval/queryOrderManageList',
                payload: {
                    cstName: values.cstName,
                    orderNo: values.orderNo,
                    contractNo: values.contractNo,
                    declarationType: values.declarationType,
                    status: values.status,
                    submitBegin: values.submitTime ? values.submitTime[0].format(Constants.DATEFORMAT) : undefined,
                    submitEnd: values.submitTime ? values.submitTime[1].format(Constants.DATEFORMAT) : undefined,
                    page: newPage
                }
            });
        };

        handleReturnOrder = (record) => {
            this.props.dispatch({
                type: 'declareApproval/returnOrder',
                payload: {
                    id: record.id,
                    searchConditions: this.collectSearchCondition(),
                    gobackreason: Constants.APPROVAL_RETURN_ORDER
                }
            });
        }

        columns = [
            { title: '订单编号', dataIndex: 'orderno', key: 'orderno' },
            { title: '客户名称', dataIndex: 'companyname', key: 'companyname' },
            { title: '合同协议号', dataIndex: 'contractno', key: 'contractno' },
            { title: '报关方式', dataIndex: 'declarationtype', key: 'declarationtype',
                render: (text, record, index) => {
                    if(record.declarationtype === "1") return "综服平台报关";
                    else return "客户自行报关";
                }
            },
            { title: '进境关别', dataIndex: 'portofentryidName', key: 'portofentryidName' },
            { title: '总货值', dataIndex: 'totalamount', key: 'totalamount' },
            { title: '币种', dataIndex: 'currencytype', key: 'currencytype' },
            { title: '提交人', dataIndex: 'creatorName', key: 'creatorName' },
            { title: '提交时间', dataIndex: 'submittime', key: 'submittime' },
            { title: '出口时间', dataIndex: 'exporttime', key: 'exporttime' },
            { title: '放行时间', dataIndex: 'passtime', key: 'passtime' },
            { title: '结关时间', dataIndex: 'finishtime', key: 'finishtime' },
            {
                title: '状态', dataIndex: 'status', key: 'status',
                render: (text, record, index) => {
                    let status = Constants.ORDERSTATUS[record.status];
                    let tgyStatus = "";
                    if(record.billId && record.tgyDeclaring === '1'){
                        tgyStatus = `(通关易：${ record.tgyStatus && Constants.TGY_STATUS[record.tgyStatus] ? Constants.TGY_STATUS[record.tgyStatus] : "尚未同步，请等待"})`
                    }
                    if ("报关中" == status) {
                        if (!R.isEmpty(record.passtime) && !R.isNil(record.passtime)) {
                            if (!R.isEmpty(record.finishtime) && !R.isNil(record.finishtime)) {
                                status += "已结关";
                            } else {
                                status += "已放行";
                            }
                        }
                        if (!R.isEmpty(record.url) && !R.isNil(record.url)) {
                            status += "已上传";
                        } else {
                            status += "未上传";
                        }
                    }
                    return status + tgyStatus
                }
            },
            {
                title: '操作', key: 'key_oprator',
                render: (text, record, index) => {
                    let split = <span className="ant-divider" />
                    let costLink = <RightBox resource={RightConstants.ORDER.ORDER_APPROVAL_COST} split={true}><a href="#" onClick={this.onEditCost.bind(this, record)}>费用</a></RightBox>
                    let viewLink = <a href="#" onClick={this.onView.bind(this, record)}>查看</a>
                    let importCDLink = <RightBox resource={RightConstants.ORDER.ORDER_APPROVAL_COST_ACCEPT} split={true}><a href="#" onClick={this.onCreateImportCD.bind(this, record)}>通关受理</a></RightBox>
                    let gennerateCD = <RightBox resource={RightConstants.ORDER.ORDER_APPROVAL_GENERATE} split={true}><a href="#" onClick={this.onGenerateImportCD.bind(this, record)}>生成报关资料</a></RightBox>
                    let clearanceLink = <RightBox resource={RightConstants.ORDER.ORDER_APPROVAL_CLEARANCE} split={true}><a href="#" onClick={this.onEditClearance.bind(this, record)}>维护通关信息</a></RightBox>
                    let reDownloadLink = <RightBox resource={RightConstants.ORDER.ORDER_APPROVAL_REDOWNLOAD} split={true}><a href="#" onClick={this.onReDownload.bind(this, record)}>下载报关资料</a></RightBox>
                    let attachmenLtink = <RightBox resource={RightConstants.ORDER.ORDER_APPROVAL_ATTACH} split={true}><a href="#" onClick={this.onManageAttachment.bind(this, record)}>附件</a></RightBox>

                    let returnLink = <Popconfirm onConfirm={this.handleReturnOrder.bind(this, record)} okText="是" cancelText="否"
                        placement="leftTop" title={'订单将退回待补充资料状态，包括费用，已关联外汇，通关信息在内的信息都会被删除，请自行判断风险，是否继续？'}>
                        <a href="#">退回</a>
                    </Popconfirm>
                    returnLink = <RightBox resource={RightConstants.ORDER.ORDER_APPROVAL_RETURN_ORDER} split={true}>{returnLink}</RightBox>

                    //会员客户下的单只到生成报关资料，屏蔽一些操作
                    let csttype = record.csttype === '2'; // 2：微信转移的客户，为true的话某些操作就是null
                    costLink = csttype ? null : costLink;
                    clearanceLink = csttype ? null : clearanceLink;
                    attachmenLtink = csttype ? null : attachmenLtink;
                    returnLink = csttype ? null : returnLink;

                    let operaters = {
                        "2": <span>{importCDLink}{costLink}{attachmenLtink}{viewLink}</span>,
                        "3": <span>{costLink}{attachmenLtink}{viewLink}</span>,
                        "4": <span>{costLink}{attachmenLtink}{viewLink}</span>,
                        "5": <span>{gennerateCD}{costLink}{attachmenLtink}{viewLink}</span>,
                        "6": <span>{clearanceLink}{costLink}{reDownloadLink}{attachmenLtink}{returnLink}{viewLink}</span>,
                        "7": <span>{reDownloadLink}{costLink}{viewLink}</span>
                    }
                    return (operaters[record.status]);
                }
            }];

        render() {
            let dataSource = R.isNil(this.props.declareApproval.dataSource) ? {} : this.props.declareApproval.dataSource;
            let formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };
            const { getFieldDecorator } = this.props.form;
            let values = this.props.form.getFieldsValue();
            let pagination = {
                showTotal: total => `共 ${total} 条数据`,
                current: this.props.declareApproval.page.page,
                pageSize: this.props.declareApproval.page.size,
                total: this.props.declareApproval.page.totalRow,
                showSizeChanger: true,
                onShowSizeChange: (current, size) => {
                    let newPage = this.props.declareApproval.page;
                    newPage.size = size;
                    newPage.page = 1;
                    this.props.dispatch({
                        type: 'declareApproval/queryOrderManageList',
                        payload: {
                            cstName: values.cstName,
                            orderNo: values.orderNo,
                            contractNo: values.contractNo,
                            declarationType: values.declarationType,
                            status: values.status,
                            submitBegin: values.submitTime ? values.submitTime[0].format(Constants.DATEFORMAT) : undefined,
                            submitEnd: values.submitTime ? values.submitTime[1].format(Constants.DATEFORMAT) : undefined,
                            page: newPage
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    let newPage = this.props.declareApproval.page;
                    newPage.page = pageNumber;
                    this.props.dispatch({
                        type: 'declareApproval/queryOrderManageList',
                        payload: {
                            cstName: values.cstName,
                            orderNo: values.orderNo,
                            contractNo: values.contractNo,
                            declarationType: values.declarationType,
                            status: values.status,
                            submitBegin: values.submitTime ? values.submitTime[0].format(Constants.DATEFORMAT) : undefined,
                            submitEnd: values.submitTime ? values.submitTime[1].format(Constants.DATEFORMAT) : undefined,
                            page: newPage
                        }
                    });
                }
            }

            //统计信息
            let statistics = this.props.declareApproval.statistics;
            let title = "";
            statistics.map(item=>title = title + item.currency + ": " + item.totalAmt + " | ")
            //title = <span style={{color: 'red'}}>{"金额统计 => " + (title ? title.substr(0, title.length - 3) : "")}</span>;

            return (
                <div>
                    <Row>
                        <Col span={6}><FormItem {...formItemLayout} label={'客户名称'}>{getFieldDecorator('cstName')(<Input />)}</FormItem></Col>
                        <Col span={6}><FormItem {...formItemLayout} label={'订单编号'}>{getFieldDecorator('orderNo')(<Input />)}</FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={6}><FormItem {...formItemLayout} label={'合同协议号'}>{getFieldDecorator('contractNo')(<Input />)}</FormItem></Col>
                        <Col span={6}><FormItem {...formItemLayout} label={'报关方式'}>
                            {getFieldDecorator('declarationType')(
                                <BizParams sprCode={"declarationtype"} style={{ width: '100%' }} all={true} />
                            )}
                        </FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={6}>
                            <FormItem {...formItemLayout} label={'提交时间'}>
                                {getFieldDecorator('submitTime')(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        showTime={{ format: 'YYYY-MM-DD' }}
                                        format="YYYY-MM-DD"
                                        placeholder={['开始时间', '结束时间']}
                                    />
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={6}>
                            <FormItem {...formItemLayout} label={'状态'}>
                                {getFieldDecorator('status', {
                                    initialValue: ""
                                })(
                                    <RadioGroup style={{ width: 1400 }}>
                                        <Radio value="">全部</Radio>
                                        <Radio value="2">待通关受理</Radio>
                                        <Radio value="3">待补充资料</Radio>
                                        <Radio value="4">待签确认函</Radio>
                                        <Radio value="5">待报关</Radio>
                                        <Radio value="6">报关中</Radio>
                                        <Radio value="7">办理完毕</Radio>
                                    </RadioGroup>
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={6} style={{ float: 'right' }}>
                            <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleSearch.bind(this, true)}>查询</Button>
                        </Col>
                    </Row>
                    <Table title={() => title} rowKey={record => record.id} dataSource={this.props.declareApproval.list} columns={this.columns} bordered={true} size={'middle'} pagination={pagination} scroll={{ x: 1400 }}/>
                    <OrderDeclareDetail ref={"orderDeclareDetail"} cstId={dataSource.cstid} {...this.props.declareApproval} customs={this.props.customs} dispatch={this.props.dispatch} refreshList={this.handleSearch}/>
                </div>
            )
        }
    })
)
